package admin_api

import (
	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
	"shop/admin/admin_service"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/service"
	"shop/utils/result"
	"shop/utils/sessionutil"
	"shop/utils/validateutil"
)

// SendPhoneVerifyCode 发送手机验证码
func SendPhoneVerifyCode(ctx *gin.Context) {
	phone := ctx.Query("phone")
	if !validateutil.ValidatePhone(phone) {
		result.RenderResult(ctx, result.Fail("手机格式不正确: "+phone))
		return
	}

	count := int64(0)
	dao.GetDB().Table(entity.TableNameSysUser).Where("phone", phone).Count(&count)
	if count == 0 {
		result.RenderFail(ctx, "账号不存在")
		return
	}
	result.RenderResult(ctx, service.SendPhoneVerifyCode(phone, constant.CacheKeyPrefixVerifyCodeSysUserLogin, 600, 3))
}

func Login(ctx *gin.Context) {
	params := admin_service.LoginParams{}
	err := ctx.ShouldBindJSON(&params)
	if err != nil {
		result.RenderFail(ctx, "参数格式错误")
		return
	}
	result.RenderResult(ctx, admin_service.Login(&params))
}

func LoginByPhone(ctx *gin.Context) {
	phone := ctx.Query("phone")
	if !validateutil.ValidatePhone(phone) {
		res := result.Fail("手机格式不正确")
		seelog.Errorf(res.Msg)
		result.RenderResult(ctx, res)
		return
	}

	result.RenderResult(ctx, admin_service.LoginByPhone(phone, ctx.Query("code")))
}

func Logout(ctx *gin.Context) {
	result.RenderResult(ctx, result.Ok(sessionutil.AdminLogout(sessionutil.GetUserIdFromCtx(ctx))))
}
